package dnl.confij.apps;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import dnl.confij.DirBasedConfigLoader;
import dnl.confij.UserHomeConfigLoader;

@SuppressWarnings("unchecked")
public class ApplicationConfiguration {
	private String name;

	private Persister persister = new XStreamPersister();
	private DirBasedConfigLoader configLoader;

	private File configFile;

	public ApplicationConfiguration(String name) {
		this.name = name;
		configLoader = new UserHomeConfigLoader(name);
	}

	public String getName() {
		return name;
	}

	public File getConfigDir() {
		return configLoader.getConfigDir();
	}

	public File getConfigFile() {
		if (configFile == null) {
			configFile = new File(configLoader.getConfigDir(), name + ".config");
		}
		return configFile;
	}

	public void saveConfigObject(String id, Object object) {
		Map<String, Object> configMap = null;
		if(!getConfigFile().exists()){
			configMap = new HashMap<String, Object>();
		}
		else {
			configMap = (Map<String, Object>) persister.load(getConfigFile());
		}
		configMap.put(id, object);
		persister.save(getConfigFile(), configMap);
	}

	public Object getConfigObject(String id) {
		if (!getConfigFile().exists()) {
			return null;
		}
		Map<String, Object> configMap = (Map<String, Object>) persister.load(getConfigFile());
		return configMap.get(id);
	}

	public void saveFileList(String id, List<File> fileList) {
		Set<File> fs = new HashSet<File>(fileList);
		saveConfigObject(id, fs);
	}

	public void addToFileList(String id, File file) {
		Set<File> fs = (Set<File>) getConfigObject(id);
		if(fs == null){
			fs = new HashSet<File>();
		}
		fs.add(file);
		saveConfigObject(id, fs);
	}

	public List<File> getFileList(String id) {
		Set<File> fs = (Set<File>) getConfigObject(id);
		if (fs == null) {
			return Collections.emptyList();
		}
		// remove any non existing files
		for (Iterator<File> iterator = fs.iterator(); iterator.hasNext();) {
			File file = iterator.next();
			if(!file.exists()){
				iterator.remove();
			}
		}
		return new ArrayList<File>(fs);
	}
}
